﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace ETModel
{
    /// <summary>
    /// DLL加载工具
    /// </summary>
	public static class DllHelper {
        /// <summary>
        /// 热更库的dll文件名
        /// </summary>
        public static string ETHotfixDllFilePath = "./ET.Server.Hotfix.dll";
        /// <summary>
        /// 热更库的dll文件名
        /// </summary>
        public static string ETHotfixPdbFilePath = "./ET.Server.Hotfix.pdb";

        /// <summary>
        /// 用户热更库的dll文件名
        /// </summary>
        public static string ETUserHotfixDllFilePath = "";
        /// <summary>
        /// 用户热更库的[db文件名
        /// </summary>
        public static string ETUserHotfixPdbFilePath = "";

        static DllHelper() {
            //从byte[]加载的程序集,如果有依赖,则走这里
            AppDomain.CurrentDomain.AssemblyResolve += (sender, arg) => {
                var assemblyName = arg.Name.Split(',').FirstOrDefault();
                if (string.IsNullOrEmpty(assemblyName)) return null;
                var assemblyFile = "./" + assemblyName + ".dll";
                if (!File.Exists(assemblyFile)) return null;
                byte[] buffer = File.ReadAllBytes(assemblyFile);
                return Assembly.Load(buffer);
            };
        }

        /// <summary>
        /// 加载热更库的程序集
        /// </summary>
        /// <returns></returns>
        public static Assembly GetHotfixAssembly() {
            byte[] dllBytes = File.ReadAllBytes(ETHotfixDllFilePath);
            byte[] pdbBytes = File.ReadAllBytes(ETUserHotfixPdbFilePath);
            //todo:到时候pdb文件要去除?
            Assembly assembly = Assembly.Load(dllBytes, pdbBytes);
            return assembly;
        }
        /// <summary>
        /// 加载用户热更库的程序集
        /// </summary>
        /// <returns></returns>
        public static Assembly GetUserHotfixAssembly() {
            if (string.IsNullOrEmpty(ETUserHotfixDllFilePath)) {
                throw new System.Exception("未初始化服务,请调用ServerManager.Init");
            }
            byte[] dllBytes = File.ReadAllBytes(ETUserHotfixDllFilePath);
            byte[] pdbBytes = File.ReadAllBytes(ETUserHotfixPdbFilePath);
            Assembly assembly = Assembly.Load(dllBytes, pdbBytes);
            return assembly;
        }
    }
}
